package com.gitee.xmhzzz.component.spring.cloud.component.dao.Generator;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;

import java.util.Collections;
import java.util.Scanner;

/**
  * @ClassName
  * @Description
  * @Author wzq
  * @Date 2023/12/15 16:56
  * @Version 1.0
  */
public class DaoGenerator {
    public String scanner(String tip)
    {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if(scanner.hasNext())
        {
            String ipt = scanner.next();
            if(StringUtils.isNotEmpty(ipt))
            {
                return ipt;
            }
        }

        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public void generateCode(String url, String userName, String password,
                             String basePackage, String author,String tablePrefix)
    {

        FastAutoGenerator.create(url, userName, password)
                .globalConfig(builder -> {
                    builder.author(author) // 设置作者
                            .enableSwagger() // 开启 swagger 模式
                            .outputDir(System.getProperty("user.dir")+"\\src\\main\\java"); // 指定输出目录
                })
                .packageConfig(builder -> {
                    builder.parent(basePackage) // 设置父包名
                            .moduleName("") // 设置父包模块名
                            .service("")
                            .controller("")
                            .serviceImpl("")
                            .mapper("")
                            .entity("")
                            .pathInfo(Collections.singletonMap(OutputFile.xml, System.getProperty("user.dir") + "\\src\\main\\resources\\mapper")); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.addInclude(scanner("表名，多个英文逗号分割").split(",")) // 设置需要生成的表名
                            .addTablePrefix(tablePrefix)// 设置过滤表前缀
                            .entityBuilder()
                            .enableLombok()
                            .build();

                })
                .templateConfig(builder -> {
                    builder.controller(null)
                            .service(null)
                            .serviceImpl(null)
                            .build();
                })
                .injectionConfig(builder -> {
                    builder.beforeOutputFile((tableInfo, objectMap)->{

                    });
                })
                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板，默认的是Velocity引擎模板
                .execute();
    }
}
